<template>
	<view class="container">
		<view class="top">
			<view class="top-box">
				<view class="person-img" @click="changeAvatar">
					<image :src="avatar" class="img-100 border-r50" mode=""></image>
				</view>
				<view class="person-text margin-b-10 margin-t-20">
					<view class="fs-16 fb ">
						{{this.realName}}
					</view>
					<view class="text-1 margin-t-10">
						{{this.orgName}}
					</view>
				</view>
				<view class="box-bottom flex flex-between">
					<view class="border-bottom-left" link @click="openMessage">
						<view class="bottom-icon flex flex-center-h algin-i-c color-w position-r" >
							<text class="iconfont iconlingdang"></text>
							<view  class="position-a" :class="{'badge-l':messageNumber,'border-r50':messageNumber}">{{messageNumber}}</view>
							<!-- <uni-badge class="badge-l" :text="messageNumber" size="small" type="error"></uni-badge> -->
						</view>
						<view class="text-1">
							系统消息
						</view>
					</view>
					<view class="border-bottom-right" link @click="openRemind">
						<view class="bottom-icon bottom-icon flex flex-center-h algin-i-c position-r">
							<text class="color-w iconfont iconlaba"></text>
							<view class="position-a" :class="{'badge-l':remindNumber,'border-r50':remindNumber}">{{remindNumber}}</view>
							<!-- <uni-badge class="badge-l" :text="remindNumber" size="small" type="error"></uni-badge> -->
						</view>
						<view class="text-1">
							预警提醒
						</view>
					</view>
				</view>
			</view>
		</view>
			<uni-list class="list-content">
				<view class="">
					<uni-list-item class="content-item top-content-item" :show-arrow="true" v-for="(item,index) in titles" :key="index" link @click="itemClick(index)" :title="item"></uni-list-item>
					<uni-list-item class="content-item top-content-item" :show-arrow="true"  link @click="handleTel" title="客服电话"></uni-list-item>
				</view>
				<view class="">
					<uni-list-item class=" content-item" :show-arrow="true" link @click="changePsw" title="修改密码"></uni-list-item>
					<uni-list-item  class="content-item" :show-arrow="true" link @click="signOut" title="退出登录"></uni-list-item>
				</view>
			</uni-list>
		<view class="QR-box click-pointer" v-if="showQR" link  id="close-qr" @click="closeQR">
			<view class="box" @click.stop="!closeQR">
				<view class="fs-14 fb">
					二维码下载
				</view>
				<view class="QR-img-box flex flex-center-h algin-i-c">
					<!-- <image class="QR-img" :src="imgUrl" mode=""></image> -->
					<tki-qrcode  class="QR-img"  cid="qrcode1" ref="qrcode" :val="val" :size="size" :unit="unit" :background="background" :foreground="foreground" :pdground="pdground" :icon="icon" :iconSize="iconsize" :lv="lv" :onval="onval" :loadMake="loadMake" :usingComponents="true" @result="qrR" />
					<!-- <canvas v-show="canvasShow" class="QR-img" canvas-id="mycanvas"></canvas> -->
				</view>
				<view class="fs-14 tc">
					<!-- 项目全生命周期管理APP -->
				</view>
				<view class="QR-bottom margin-t-10 tr">
					<!-- <span class="fs-14 theme-color" @click="saveImg">保存图片</span> -->
					<span class="margin-l-10 fs-14 theme-color" @click="confirm">确定</span>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {logout} from '@/common/api/api.js'
	import {changePassword,messageNumber,user,pdfFile,remindWarningNumber,upload,fileByNmae,fileById,lastestVersionUrl,lastestVersion} from '@/common/api/profile.js'
	import ipConfig from '@/utils/ipconfig.js'

	export default {
		data() {
			return {
				titles:['版本更新','二维码下载','版本信息','清除缓存','使用帮助','意见反馈'],
				showQR:false,
				QRUrl:null,
				avatar:null,
				realName:null,
				orgName:null,
				userDto:{},
				messageInfo:{
					userPhoneList:[
						{
							userId:"",
							phone:""
						}
					]
				},
				messageNumber:'',
				remindNumber:'',
				canvasShow:true,
				imgUrl:null,
				val: '二维码', // 要生成的二维码值
				size: 250, // 二维码大小
				unit: 'upx', // 单位
				background: '#eee', // 背景色
				foreground: '#666', // 前景色
				pdground: '#444', // 角标色
				icon: '', // 二维码图标
				iconsize: 40, // 二维码图标大小
				lv: 3, // 二维码容错级别 ， 一般不用设置，默认就行
				onval: false, // val值变化时自动重新生成二维码
				loadMake: true, // 组件加载完成后自动生成二维码
				src: '' // 二维码生成后的图片地址或base64
			}
		},
		onShow() {
			this.getUserInfo();
			this.getMessage();
			this.getRemindWarning();
		},
		onLoad() {
			this.userDto.phone = uni.getStorageSync('user_info').phone;
			this.userDto.username = uni.getStorageSync('user_info').username;
			this.getUserInfo();
		},
		methods: {
			itemClick(n){
				switch(n){
					case 0 : this.openUpdate();break;
					case 1 : this.openQR();break;
					case 2 : this.openInformation();break;
					case 3 : this.openClear();break;
					case 4 : this.openHelp();break;
					case 5 : this.openOpinion();break;
				}
			},
			// 客服电话
			handleTel(){
				uni.makePhoneCall({
				    phoneNumber: '12345678910' //仅为示例
				});
			},
			getUserInfo(){//展示用户信息
				let user_info = uni.getStorageSync('user_info');
				this.avatar = user_info.avatar;
				this.realName = user_info.realName;
				this.orgName = user_info.orgName;
				this.userId = user_info.id;
				let fileName = this.avatar.replace(/"/g,'');
				fileByNmae(fileName).then((res)=>{
					this.avatar = 'data:application/force-download;base64,' + uni.arrayBufferToBase64(res);
				})
			},
			getMessage(){//获取消息
				this.messageInfo.userPhoneList[0].userId = uni.getStorageSync('user_info').id;
				this.messageInfo.userPhoneList[0].phone = uni.getStorageSync('user_info').phone;
				messageNumber().then( res => {
					if(res.code === "20000"){
						this.messageNumber = res.data ? res.data : null;
					}
				})
			},
			getRemindWarning(){//获取预警消息
				let id = uni.getStorageSync('user_info').id;
				remindWarningNumber().then( res => {
					if(res.code === "20000"){
						this.remindNumber = res.data.count ? res.data.count : null;
						// if(this.remindNumber){
						// 	uni.showModal({
						// 		title:'提示',
						// 		content:`您有${this.remindNumber}条新任务，请立即前往查看并处理!`,
						// 		confirmText:'立即处理',
						// 		success: (res) => {
						// 			if(res.confirm){
						// 				this.openRemind();
						// 			}
						// 		}
						// 	})
						// }
					}
				})
			},
			getNewUser(){//修改头像后刷新用户信息
				user(this.userId).then(res => {
					if(res.code === "20000"){
						uni.setStorageSync('user_info',res.data);
						this.userDto.phone = uni.getStorageSync('user_info').phone;
						this.userDto.username = uni.getStorageSync('user_info').username;
						this.getUserInfo();
					}
				})
			},
			closeQR(){
				this.showQR = false;
			},
			openMessage(){//打开消息
				uni.navigateTo({
					url:'/pages/Personal/Message/Message?'
				})
			},
			openRemind(){//打开预警消息
				uni.navigateTo({
					url:'/pages/Personal/RemindWarning/RemindWarning'
				})
			},
			openQR(){//打开下载二维码
				this.showQR = true;
				this.val = ipConfig.ip + 'admin/sysappversion/getLastestVersionUrl';
			},
			saveQrcode() {	//保存二维码
				this.$refs.qrcode._saveCode()
			},
			qrR(res) {
				this.src = res
			},
			openUpdate(){	//版本更新
				let appVersion = ''
				uni.getSystemInfo({
					success: function(e) {
						appVersion = e.platform;
					}
				})
				plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
					lastestVersion().then( res => {	//此处为访问后台是否有更新
						if (res.data.versionNum > parseInt(wgtinfo.versionCode)) {
								uni.showModal({
									title: "发现新版本",
									// content: res.data.updateInstructions, //更新描述
									confirmText:'立即更新',
									cancelText:'稍后进行',
									success: sucRes => {
										if (sucRes.confirm) {
											//如果是安卓直接更新下载
											if(appVersion == 'android'){
												uni.showLoading({
													title: '新版本后台下载中，请稍等',
												})
												uni.downloadFile({
													url: ipConfig.ip + 'admin/sysappversion/getLastestVersionUrl',
													success: data => {
														if (data.statusCode === 200) {
															uni.hideLoading();
															plus.runtime.install(data.tempFilePath, {
																force: true 
															}, function() {
																plus.runtime.restart();  
															});  
														 }  
													},
													complete(res) {
														console.log(res)
													}
												})
											}
										}
									}
								})
						}else{
								uni.showToast({icon:'none',title:'当前已是最新版本'})
						}
					})
				})
			
			},
			openInformation(){//版本信息
				plus.runtime.getProperty(plus.runtime.appid, (wgtinfo)=> {
					lastestVersion().then(res => {
						uni.showModal({
							title: `当前版本：${wgtinfo.version}`,
							content: res.data.updateInstructions,
							showCancel:false
						})
					})
					
				})
			},
			formatSize() {  
				let that = this;  
				plus.cache.calculate(function(size) {  
					let sizeCache = parseInt(size);
					if (sizeCache == 0) {  
						that.fileSizeString = "0B";  
					} else if (sizeCache < 1024) {  
						that.fileSizeString = sizeCache + "B";  
					} else if (sizeCache < 1048576) {  
						that.fileSizeString = (sizeCache / 1024).toFixed(2) + "KB";  
					} else if (sizeCache < 1073741824) {  
						that.fileSizeString = (sizeCache / 1048576).toFixed(2) + "MB";  
					} else {  
						that.fileSizeString = (sizeCache / 1073741824).toFixed(2) + "GB";  
					}  
				});  
			},
			openClear(){ //清除缓存
				let that = this;  
				let os = plus.os.name;  
				if (os == 'Android') {  
					let main = plus.android.runtimeMainActivity();  
					let sdRoot = main.getCacheDir();  
					let files = plus.android.invoke(sdRoot, "listFiles");  
					let len = files.length;  
					for (let i = 0; i < len; i++) {  
						let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
						plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
							if (entry.isDirectory) {  
									entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录  
										uni.showToast({  
												title: '缓存清理完成',  
												duration: 2000  
										});  
										that.formatSize(); // 重新计算缓存  
									}, function(e) {
										uni.showToast({
												title: e.message,
												duration: 2000  
										});
										console.log(e.message)  
									});  
							} else {  
								entry.remove();
							}  
						}, function(e) {  
								console.log('文件路径读取失败')  
						});  
					}  
				} else { // ios  
					plus.cache.clear(function() {  
						uni.showToast({  
								title: '缓存清理完成',  
								duration: 2000  
						});  
						that.formatSize();  
					});  
				}
			},
			openHelp(){	//使用帮助
				uni.navigateTo({
					url: '/pages/Personal/PrePDF/PrePDF'
				})
			},
			openOpinion(){//意见反馈
				uni.navigateTo({
					url:'/pages/Personal/Opinion/Opinion'
				})
			},
			changePsw(){//修改密码
				uni.navigateTo({
					url:'/pages/Personal/ChangePSD/ChangePSD'
				})
			},
			signOut(){	//退出登录
				uni.showModal({
					title:"提示",
					content:"是否确认退出?",
					success:res => {
						if(res.confirm){
							uni.redirectTo({
								url:'/pages/Login/Login',
								success: (res) => {
									logout().then(res => {}) 
								}
							})
						}
					}
				})
			},
			confirm(){//二维码确认按钮
				this.showQR = false;
			},
			saveImg(){//二维码保存按钮
				this.saveQrcode();
				this.showQR = false;
			},
			changeAvatar(){//修改头像
				uni.chooseImage({
					count:1,
					sizeType:['original', 'compressed'],
					sourceType:['album','camera'],
					success: (res) => {
						uni.uploadFile({
							url: ipConfig.ip + 'admin/sys-file/upload?path=avatar', 
							filePath: res.tempFilePaths[0],
							name: 'file',
							header: {'Authorization': 'Bearer '+ uni.getStorageSync('token')},
							success: (res1) => {
								if(res1.statusCode == 200){
									let id = JSON.parse(res1.data).data.id;
									fileById(id).then( res2 => {
										const base64 = 'data:application/force-download;base64,' + uni.arrayBufferToBase64(res2)
										this.avatar = base64;
										this.userDto.avatar = JSON.parse(res1.data).data.fileName;
										this.userDto.userId = uni.getStorageSync('user_info').id;
										changePassword(this.userDto).then( res3 => {
											this.getNewUser();
											uni.showToast({
												title: '头像修改成功',
												icon: 'none'
											})
										})
									})
								}
							}
						});
					}
				})
			}
		}
	}
</script>

<style scoped>
.uni-list-item{padding: 0 1%;line-height: 16px;border-bottom: 2rpx solid #F2F2F2;}
/* .uni-list:after,.uni-list::before{background-color: transparent!important;} */
.uni-list /deep/ .uni-list--border-bottom,.uni-list /deep/ .uni-list--border-top{background-color: transparent!important;}
.QR-box{position: fixed;background-color: rgba(1,1,1,0.2);z-index: 999;top: 0;bottom: -10px;width: 100%;display: block;}
.box{background-color: #FFF;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);width: 350px;height: 350px;padding: 20px;border-radius: 10px;box-sizing: border-box;}
.QR-img-box{height: 250px;}
.QR-img{width: 180px;height: 180px;}
.QR-img /deep/ uni-image{width: 100%!important;height: 100%!important;}
.text-1{font-size: 13px;color: #888;}
.container{background-color: #eee;position: relative;}
.list-content{position: absolute;bottom: 10px;top: 270px;overflow: auto;width: 100%;background-color: #eee;}
.list-content /deep/ .uni-list-item{height: 40px;align-items: center;}
.top{height: 100px;width: 100%;background-color: #09AAE9;margin-bottom: 130px;position: relative;padding-top:50px ;}
.top-box{border-radius: 10px;background-color: #FFFFFF;top: 20px;position: relative;margin: 10px;padding: 15px 50px;text-align: center;}
.person-img{position: absolute;top: 0;left: 50%;height: 70px;width: 70px;background-color: #32dbc6;border-radius: 50%;transform: translate(-50%,-50%);}
.bottom-icon{width: 40px;height: 40px;background-color: #09AAE9;border-radius: 50%;margin: 5px;position: relative;}
.pdf-content{position: fixed;top: 0;bottom: 0; left: 0;right: 0;}
.content-item /deep/ .uni-list--border:after{height: 0px!important;}
.top-content-item:last-child{margin-bottom: 5px!important;}
</style>
